

#import "FTWNetworkTools.h"
#import "NSString+Hash.h"
#import "SSKeychain.h"

@implementation FTWNetworkTools

+(instancetype)sharedTools{
    static FTWNetworkTools *instance;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[self alloc] init];
    });
    return instance;
}

-(instancetype)init{
    self = [super init];
    if(self){
        
        //读取钥匙串
        [self loadUserInfo];
    }
    return self;
}

-(void)loginwithUrlString:(NSString *)urlString sucess:(void(^)())sucessBlock error:(void(^)(NSString *error))errorBlock{
    //POST
    NSURL *url = [NSURL URLWithString:@"http://127.0.0.1/php/loginhmac.php"];
    
    //请求
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    //GET_>POST
    request.HTTPMethod = @"POST";
    //3.MD5+时间
    //    self.password = [self md5Time:self.password];
    
    NSString *psw = [self md5Time:self.password];
    //    NSLog(@"%@",password);
    
    //请求体 username=zhangsan&password=zhangsan
    NSString *bodyString = [NSString stringWithFormat:@"username=%@&password=%@",self.username,psw];
    request.HTTPBody = [bodyString dataUsingEncoding:NSUTF8StringEncoding];
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    NSDictionary *dict = @{@"username":self.username,@"password":psw};
    [manager POST:urlString parameters:dict success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *dict = responseObject;
        if([dict[@"userId"] intValue] == 1){

          if(sucessBlock)
                sucessBlock();

            [self saveUserInfo];
        }else{
            //                NSLog(@"登陆失败");
            if(errorBlock)
                errorBlock(@"账号密码错误");
            
        }

        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if(errorBlock)
            errorBlock(@"网络错误");
    }];
        
}

//MD5+时间校验
/*
 一个字符串key    md5计算
 把原密码和之前生成的md5值再进行hmac加密
 从服务器获取当前时间 到分钟 的字符串
 第二步产生的hmac值+时间      和第一步产生的md5值进行hmac加密
 */
-(NSString *)md5Time:(NSString *)string{
    NSString *key = @"itcast";
    NSString *md5 = [key md5String];
    NSString *hmac = [string hmacMD5StringWithKey:md5];
    
    //获取服务器的时间
    NSURL *url = [NSURL URLWithString:@"http://127.0.0.1/php/hmackey.php"];
    NSData *data = [NSData dataWithContentsOfURL:url];
    
    //json反序列化
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL];
    NSString *time = dic[@"key"];
    
    return [[hmac stringByAppendingString:time] hmacMD5StringWithKey:md5];
}

#define kUSERNAME @"username"
#define kPASSWORD @"password"
#define APPID [NSBundle mainBundle].bundleIdentifier

// 保存数据到偏好设置
-(void)saveUserInfo{
    
    NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
    
    [ud setObject:self.username forKey:kUSERNAME];
    //    [ud setObject:[self base64Encoder:self.tf_password.text] forKey:kPASSWORD];
    //密码存到系统的钥匙串中
    
    /*
     1.要存储的密码
     2.指定APP的标识
     3.指定app中哪个用户名
     */
    [SSKeychain setPassword:self.password forService:APPID account:self.username];
    
    [ud synchronize];
    
}

//取数据
-(void)loadUserInfo{
    NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
    self.username = [ud objectForKey:kUSERNAME];
    //    self.tf_password.text = [ud objectForKey:kPASSWORD];
    //    NSString *base64Str = [ud objectForKey:kPASSWORD];
    //    if(base64Str)
    //    self.tf_password.text = [self base64Decoder:base64Str];
    
    /*
     1.指定APP的标识
     2.指定app中哪个用户名
     */
    self.password = [SSKeychain passwordForService:APPID account:self.username];
}

@end
